package net.zjitc.dao.impl;

import net.zjitc.dao.ProductDao;
import net.zjitc.domain.product;
import net.zjitc.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author admin
 * @Date 2019/2/25 9:20
 */
public class ProductDaoImpl implements ProductDao {
    @Override
    public List<product> findAll() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from product";
        List<product>list = (List<product>) queryRunner.query(sql,new BeanListHandler(product.class));
        return list;
    }

    @Override
    public void delete(String pid) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "delete from product where pid = ?";
        queryRunner.update(sql,pid);
    }

    @Override
    public void add(product product) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "insert into product(pname,marketprice,shopprice,ishot,pdesc,image) values(?,?,?,?,?,?)";
        queryRunner.update(sql,new Object[]{product.getPname(),product.getMarketprice(),product.getShopprice(),product.getIshot(),product.getPdesc(),product.getImage()});
    }

    @Override
    public product findByID(int pid) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from product where pid = ?";
        product products = (product) queryRunner.query(sql,new BeanHandler(product.class),pid);
        return products;
    }

    @Override
    public void edit(product product, String pid) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "update product set pname = ?,marketprice=?,shopprice=?,ishot=?,pdesc=?where pid = ?";
        queryRunner.update(sql,new Object[]{product.getPname(),product.getMarketprice(),product.getShopprice(),product.getIshot(),product.getPdesc(),pid});

    }
}
